<template>
    <div>
        <!-- 导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 用户列表主体 -->
        <el-card>
            <!-- 搜索区域 -->
                <el-row :gutter="25">
                <el-col :span="10">
                    <el-input 
                    placeholder="请输入搜索内容" 
                    v-model="queryInfo.query" 
                    clearable
                    @clear="getUserList"
                    >
                    <template #append>
                        <el-button 
                        icon="el-icon-search" 
                        @click="getUserList"
                        ></el-button>
                    </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" icon="el-icon-plus" @click="addUser">
                    添加用户
                    </el-button>
                </el-col>
                </el-row>
            <!-- 用户列表部分 -->
            <!-- 在用户列表部分添加新的列 -->
            <el-table :data="userList" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="密码" prop="password"></el-table-column>
            <el-table-column label="角色" prop="role"></el-table-column>
            <!-- 添加工作所在地列 -->
            <el-table-column label="工作所在地" prop="workLocation"></el-table-column>
            <!-- 添加电话列 -->
            <el-table-column label="电话" prop="phone"></el-table-column>
            <el-table-column label="状态" prop="state">
                <template v-slot:default="scope">
                <el-switch v-model="scope.row.state"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template v-slot:default="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                </template>
            </el-table-column>
            </el-table>

                <!-- 分页组件 -->
                 <div>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pageNum"
                        :page-sizes="[1, 2, 5, 100]"
                        :page-size="queryInfo.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                 </div>
        </el-card>
       <!-- 添加用户对话框 -->
            <el-dialog title="添加用户" v-model="addUserDialogVisible" width="50%">
            <el-form :model="addUserForm" :rules="addUserRules" label-width="120px">
                <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                <el-input v-model="addUserForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                <el-select v-model="addUserForm.role" placeholder="请选择角色" style="width: 100%">
                    <el-option label="管理员" value="admin"></el-option>
                    <el-option label="普通用户" value="user"></el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="工作所在地" prop="workLocation">
                <el-input v-model="addUserForm.workLocation"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                <el-input v-model="addUserForm.phone"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                <el-button @click="addUserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddUser">确 定</el-button>
                </span>
            </template>
            </el-dialog>
            <!-- 编辑用户对话框 -->
            <el-dialog title="编辑用户" v-model="editUserDialogVisible" width="50%">
                <el-form :model="editUserForm" :rules="addUserRules" label-width="120px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editUserForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editUserForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="editUserForm.password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="角色" prop="role">
                        <el-select v-model="editUserForm.role" placeholder="请选择角色" style="width: 100%">
                            <el-option label="管理员" value="admin"></el-option>
                            <el-option label="普通用户" value="user"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工作所在地" prop="workLocation">
                        <el-input v-model="editUserForm.workLocation"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="phone">
                        <el-input v-model="editUserForm.phone"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editUserDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submitEditUser">确 定</el-button>
                    </span>
                </template>
            </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    created() {
        this.getUserList()
    },
    data() {
        return {
            // 查询信息实体
            queryInfo: {
                query: '',
                pageNum: 1,
                pageSize: 5
            },
            userList: [],
            total: 0,

            // 控制添加用户对话框显示
            addUserDialogVisible: false,
            // 控制编辑用户对话框显示
            editUserDialogVisible: false,
            // 添加用户表单数据
            addUserForm: {
                username: '',
                email: '',
                password: '',
                role: '',
                workLocation: '',
                phone: ''
            },
            // 编辑用户表单数据
            editUserForm: {
                id: '',
                username: '',
                password: '',
                email: '',
                role: '',
                workLocation: '',
                phone: ''
            },

            // 表单验证规则
            addUserRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ],
                role: [
                    { required: true, message: '请选择角色', trigger: 'change' }
                ],
                workLocation: [
                    { required: true, message: '请输入工作所在地', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ]
            }
            }
        },
    methods: {
        // 获取用户列表
        async getUserList() {
            
                const { data: res } = await this.$http.get('allUser', {
                    params: this.queryInfo
                });

                console.log('接口返回结果:', res); 
                this.userList = res.data; // 更新用户列表
                this.total = res.numbers; // 更新总记录数
            
        },
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.getUserList();
        },
        handleCurrentChange(newPage) {
            this.queryInfo.pageNum = newPage;
            this.getUserList();
        },
        addUser() {
            this.addUserDialogVisible = true;
        },
        editUser() {
            this.editUserDialogVisible = true;
        },
        // 提交新增用户
        async submitAddUser() {
            try {
                const response = await axios.post('/user/add', this.addUserForm);

                if (response.data.code === 200) {
                    this.$message.success('用户添加成功');
                    this.addUserDialogVisible = false; // 关闭弹窗
                    this.getUserList(); // 刷新用户列表
                } else {
                    this.$message.error(response.data.message || '用户添加失败');
                }
            } catch (error) {
                console.error('添加用户失败:', error);
                this.$message.error('请求失败，请稍后再试');
            }
        },

        // 获取用户列表
        async getUserList() {
            try {
                const { data: res } = await this.$http.get('allUser', {
                    params: this.queryInfo
                });

                this.userList = res.data;
                this.total = res.numbers;
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('获取用户列表失败，请检查网络或后端服务');
            }
        },
        // 打开编辑用户对话框并赋值
        async editUser(id) {
            try {
                const { data: res } = await this.$http.get(`user/${id}`);
                if (res.code === 200) {
                    this.editUserForm = res.data;
                    this.editUserDialogVisible = true;
                } else {
                    this.$message.error('获取用户信息失败');
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                this.$message.error('请求失败，请稍后再试');
            }
        },
        // 提交编辑后的用户信息
        async submitEditUser() {
            try {
                const response = await this.$http.post('/user/update', this.editUserForm);

                if (response.data.code === 200) {
                    this.$message.success('用户信息更新成功');
                    this.editUserDialogVisible = false;
                    this.getUserList(); // 刷新列表
                } else {
                    this.$message.error(response.data.message || '更新失败');
                }
            } catch (error) {
                console.error('更新用户失败:', error);
                this.$message.error('请求失败，请稍后再试');
            }
        },
        // 删除用户
        async deleteUser(id) {
            try {
                const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                if (confirmResult === 'confirm') {
                    const { data: res } = await this.$http.delete(`user/delete/${id}`);

                    if (res.code === 200) {
                        this.$message.success('用户删除成功');
                        this.getUserList();
                    } else {
                        this.$message.error(res.message || '删除失败');
                    }
                }
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('请求失败，请稍后再试');
                }
            }
        }
    }
}
</script>